package com.example.CarManagement.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.CarManagement.common.Result;
import com.example.CarManagement.enumPojo.ApplicationStatus;
import com.example.CarManagement.enumPojo.ApprovalsDecision;
import com.example.CarManagement.enumPojo.DriverStatus;
import com.example.CarManagement.enumPojo.OrderStatus;
import com.example.CarManagement.sys.dto.DispatchDto;
import com.example.CarManagement.sys.entity.*;
import com.example.CarManagement.sys.mapper.*;
import com.example.CarManagement.sys.service.IApplicationsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

import static com.example.CarManagement.Utils.sysUtils.createId;

/**
 * <p>
 * 用车申请表，记录用户提交的用车申请及审批状态 服务实现类
 * </p>
 *
 * @author 徐佳彪
 * @since 2025-07-17
 */
@Service
public class ApplicationsServiceImpl extends ServiceImpl<ApplicationsMapper, Applications> implements IApplicationsService {

    @Resource
    private UserServiceImpl userService;


    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;


    @Resource
    private ApprovalFlowsMapper approvalFlowsMapper;


    @Resource
    private ApprovalsMapper approvalsMapper;


    @Resource
    private CarInfoMapper carInfoMapper;


    @Resource
    private DriversMapper driversMapper;


    @Resource
    private OrdersMapper ordersMapper;


    @Value("${sysRoleId.admin}")
    private String adminRoleId;

    @Value("${sysRoleId.driver}")
    private String driverRoleId;


    @Override
    public Result<?> add(Applications applications) {
        // 生产基础信息
        applications.setId(UUID.randomUUID().toString());

        String applicationNumber = createId("APP");

        applications.setApplicationNumber(applicationNumber);

        applications.setStatus(ApplicationStatus.pending);

        applications.setCreatedAt(LocalDateTime.now());
        applications.setUpdatedAt(LocalDateTime.now());

        // 分配审核人员
        // 查询第一个步骤需要的权限
        User user = randomUser(1);
        if (user != null) {
            applications.setCurrentApproverId(user.getId());
        }

        this.baseMapper.insert(applications);

        return Result.success();
    }

    @Override
    public Result<?> selfList(String token) {
        LoginUser userInfo = userService.getUserInfo(token);


        LambdaQueryWrapper<Applications> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Applications::getApplicantId, userInfo.getUser().getId());

        List<Applications> applications = this.baseMapper.selectList(queryWrapper);

        return Result.success(applications);
    }

    @Override
    public Result<?> needApproveList(String token, Integer pageNo, Integer pageSize, String applicationNumber, String status) {
        LoginUser userInfo = userService.getUserInfo(token);
        LambdaQueryWrapper<Applications> queryWrapper = new LambdaQueryWrapper<>();

        if (applicationNumber != null) {
            queryWrapper.like(Applications::getApplicationNumber, applicationNumber);
        }
        if (status != null) {
            queryWrapper.eq(Applications::getStatus, status);
        }


        // 判断当前用户是否是超级管理员
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.eq(UserRole::getUserId, userInfo.getUser().getId());
        UserRole userRole = userRoleMapper.selectOne(userRoleLambdaQueryWrapper);
        if (!userRole.getRoleId().equals(adminRoleId)) {
            queryWrapper.eq(Applications::getCurrentApproverId, userInfo.getUser().getId());
        }


        Page<Applications> applicationsPage = this.baseMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);

        // 角色总数
        Integer total = (int) applicationsPage.getTotal();


        List<Applications> applications = applicationsPage.getRecords();

        Map<String, Object> data = new HashMap<>();
        data.put("rows", applications);
        data.put("total", total);

        return Result.success(data);
    }


    // 审核订单
    @Override
    public Result<?> review(Applications applications, Approvals approvals, String token) {
        LoginUser userInfo = userService.getUserInfo(token);
        Applications application = this.baseMapper.selectById(applications.getId());

        if (application.getStatus() != ApplicationStatus.pending) {
            return Result.fail("该申请已审批过了");
        }

        // 检查当前用户是否是当前审批人 // 如果当前用户是超级管理员 则可以直接审批
        // 检查当前用户是否是超级管理员
        if (application.getCurrentApproverId() != null && !application.getCurrentApproverId().equals(userInfo.getUser().getId())) {
            if (!userInfo.getUser().getId().equals(adminRoleId)) {
                return Result.fail("该申请已被其他人审批");
            }
        }


        // 查询审批流程
        List<ApprovalFlows> approvalFlows = approvalFlowsMapper.selectList(null);


        // 查询审批记录
        LambdaQueryWrapper<Approvals> approvalsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        approvalsLambdaQueryWrapper.eq(Approvals::getApplicationId, applications.getId());

        List<Approvals> approvalsList = approvalsMapper.selectList(approvalsLambdaQueryWrapper);


        // 创建审批记录
        Approvals newApprovals = new Approvals();
        newApprovals.setId(UUID.randomUUID().toString());
        newApprovals.setApplicationId(applications.getId());
        newApprovals.setApproverId(userInfo.getUser().getId());
        newApprovals.setApprovalStep(approvalsList.size() + 1);
        newApprovals.setDecision(approvals.getDecision());
        newApprovals.setComments(approvals.getComments());
        newApprovals.setCreatedAt(LocalDateTime.now());
        newApprovals.setDecisionTime(LocalDateTime.now());
        newApprovals.setUpdatedAt(LocalDateTime.now());
        approvalsMapper.insert(newApprovals);

        // 如果审批拒绝则更新订单状态
        if (newApprovals.getDecision() == ApprovalsDecision.rejected) {
            application.setStatus(ApplicationStatus.rejected);
            this.baseMapper.updateById(application);
            return Result.success("审批拒绝");
        }


        if (newApprovals.getApprovalStep() == approvalFlows.size()) {
            // 完成审批流程
            // 更新订单状态
            application.setStatus(ApplicationStatus.approved);
            this.baseMapper.updateById(application);


            return Result.success("审批完成");
        } else {
            // 分配审核人员
            // 查询第一个步骤需要的权限
            User user = randomUser(newApprovals.getApprovalStep() + 1);
            if (user != null) {
                application.setCurrentApproverId(user.getId());
                this.baseMapper.updateById(application);
            }

            return Result.success("审批通过");
        }
    }

    @Override
    public Result<?> detail(String id) {
        // 查询申请信息
        Applications applications = this.baseMapper.selectById(id);

        // 查询审批记录
        LambdaQueryWrapper<Approvals> approvalsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        approvalsLambdaQueryWrapper.eq(Approvals::getApplicationId, applications.getId());
        List<Approvals> approvalsList = approvalsMapper.selectList(approvalsLambdaQueryWrapper);
        List<Map<String, Object>> approvalsData = new ArrayList<>();

        for (Approvals approvals : approvalsList) {
            Map<String, Object> data = new HashMap<>();
            User user = userMapper.selectById(approvals.getApproverId());
            try {
                data.put("approverName", user.getUsername());
            } catch (Exception e) {
                data.put("approverName", "未知");
            }

            data.put("decision", approvals.getDecision());
            data.put("comments", approvals.getComments());
            data.put("decisionTime", approvals.getDecisionTime());
            approvalsData.add(data);
        }


        // 查询申请人信息
        User applicant = userMapper.selectById(applications.getApplicantId());
        applicant.setPassword(null);

        Map<String, Object> result = new HashMap<>();
        result.put("applications", applications);
        result.put("approvals", approvalsData);
        result.put("applicant", applicant);

        return Result.success(result);
    }

    @Override
    public Result<?> dispatchList(Integer pageNo, Integer pageSize, String applicationNumber) {
        LambdaQueryWrapper<Applications> queryWrapper = new LambdaQueryWrapper<>();

        if (applicationNumber != null) {
            queryWrapper.like(Applications::getApplicationNumber, applicationNumber);
        }

        // 查询所有审批通过的申请
        queryWrapper.eq(Applications::getStatus, ApplicationStatus.approved);

        Page<Applications> applicationsPage = this.baseMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);

        // 角色总数
        Integer total = (int) applicationsPage.getTotal();


        List<Applications> applications = applicationsPage.getRecords();


        // 查询所有可用车辆
        LambdaQueryWrapper<CarInfo> carInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        carInfoLambdaQueryWrapper.eq(CarInfo::getStatus, 0);
        List<CarInfo> carInfos = carInfoMapper.selectList(carInfoLambdaQueryWrapper);


        Map<String, Object> data = new HashMap<>();
        data.put("applications", applications);
        data.put("applicationsTotal", total);

        data.put("carInfos", carInfos);
        data.put("carInfosTotal", carInfos.size());


        return Result.success(data);

    }

    @Override
    public Result<?> dispatch(DispatchDto dispatchDto, String token) {
        LoginUser userInfo = userService.getUserInfo(token);

        Applications applications = dispatchDto.getApplications();

        CarInfo carInfo = dispatchDto.getCarInfo();

        if (carInfo == null || applications == null) {
            return Result.fail("参数错误");
        }
        // 判断车辆是否可用
        LambdaQueryWrapper<CarInfo> carInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        carInfoLambdaQueryWrapper.eq(CarInfo::getId, carInfo.getId());
        carInfoLambdaQueryWrapper.eq(CarInfo::getStatus, 0);
        CarInfo oldCar = carInfoMapper.selectOne(carInfoLambdaQueryWrapper);
        if (oldCar == null) {
            return Result.fail("车辆不可用");
        }

        // 判单座位是否
        if (carInfo.getSeatCount() < applications.getPassengers()) {
            return Result.fail("座位不足");
        }

        // 是否需要司机，如果需要司机则判断司机状态是否可用
        Drivers drivers = null;
        if (applications.getNeedDriver()) {
            // 判断当前车辆是否分配了司机
            LambdaQueryWrapper<Drivers> driversLambdaQueryWrapper = new LambdaQueryWrapper<>();
            driversLambdaQueryWrapper.eq(Drivers::getCurrentVehicleId, carInfo.getId());
            drivers = driversMapper.selectOne(driversLambdaQueryWrapper);
            if (drivers == null) {
                return Result.fail("车辆未分配司机");
            }
            // 判断司机是否可用
            if (drivers.getStatus() != DriverStatus.available) {
                return Result.fail("司机不可用");
            }

        }

        // 都没问题，则生产订单
        // 订单生产
        Orders orders = new Orders();
        orders.setId(UUID.randomUUID().toString());
        orders.setOrderNumber(createId("ORD"));

        orders.setApplicationId(applications.getApplicationNumber());
        orders.setDispatcherId(userInfo.getUser().getId());
        orders.setDispatchTime(LocalDateTime.now());
        orders.setVehicleId(carInfo.getId());

        if (applications.getNeedDriver() && drivers != null) {
            orders.setDriverId(drivers.getDriverId());
        }

        orders.setStatus(OrderStatus.dispatched);
        orders.setCreatedAt(LocalDateTime.now());
        orders.setUpdatedAt(LocalDateTime.now());

        ordersMapper.insert(orders);

        // 修改申请表状态
        applications.setStatus(ApplicationStatus.dispatched);
        this.baseMapper.updateById(applications);
        // 修改车辆状态
        carInfo.setStatus(1);
        carInfoMapper.updateById(carInfo);
        // 修改司机状态
        if (applications.getNeedDriver() && drivers != null) {
            drivers.setStatus(DriverStatus.on_duty);
            LambdaQueryWrapper<Drivers> oldDriversLambdaQueryWrapper = new LambdaQueryWrapper<>();
            oldDriversLambdaQueryWrapper.eq(Drivers::getDriverId, drivers.getDriverId());
            driversMapper.update(drivers, oldDriversLambdaQueryWrapper);
        }

        return Result.success("分配成功");
    }


    /**
     * 随机分配用户
     *
     * @param approvalStep 审批步骤
     * @return user 用户
     */
    public User randomUser(int approvalStep) {
        LambdaQueryWrapper<ApprovalFlows> flowsQueryWrapper = new LambdaQueryWrapper<>();
        flowsQueryWrapper.eq(ApprovalFlows::getStepNumber, approvalStep);
        ApprovalFlows flows = approvalFlowsMapper.selectOne(flowsQueryWrapper);
        // 查询拥有该权限的用户
        LambdaQueryWrapper<UserRole> roleQueryWrapper = new LambdaQueryWrapper<>();
        roleQueryWrapper.eq(UserRole::getRoleId, flows.getApproverRoleId());
        List<UserRole> userRoles = userRoleMapper.selectList(roleQueryWrapper);

        List<String> uids = new ArrayList<>();

        for (UserRole userRole : userRoles) {
            uids.add(userRole.getUserId());
        }

        // 查询用户信息
        // 随机选择一个用户
        List<User> users = userMapper.selectBatchIds(uids);
        if (users.size() > 0) {
            while (true) {
                int randomIndex = new Random().nextInt(users.size());
                User user = users.get(randomIndex);
                if (user.getStatus()) {
                    return user;
                } else {
                    users.remove(randomIndex);
                }
                if (users.size() == 0) {
                    return null;
                }
            }

        }

        return null;
    }
}
